package config

import "net"

// RaftKernelConfig is RaftKernel Configration.
type RaftKernelConfig struct {
	HaertBastTime uint64
	Port          int
	Address       string
}

// NewRaftKernelConfig is get Config instance.
func NewRaftKernelConfig(port int, haertBastTime uint64) *RaftKernelConfig {
	addr, _ := localIPv4Address()

	return &RaftKernelConfig{
		HaertBastTime: haertBastTime,
		Port:          port,
		Address:       addr,
	}
}

// localIPv4Address is get local ip address. (not localhost)
// If there are more than two addresses, it is not recommended.
func localIPv4Address() (string, error) {
	addrs, err := net.InterfaceAddrs()

	if err != nil {
		return "", err
	}

	if len(addrs) > 2 {
		return "", nil
	}

	for _, addr := range addrs {
		ip, isIP := addr.(*net.IPNet)
		if isIP && !ip.IP.IsLoopback() {
			ipv4 := ip.IP.To4()
			if ipv4 != nil {
				return ipv4.String(), nil
			}
		}
	}

	return "", nil
}
